package com.xcjw.com.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.xcjw.com.Base.Myapplication;
import com.xcjw.com.Bean.CodeBean;
import com.xcjw.com.Bean.LoginBean;
import com.xcjw.com.Bean.LoginUser;
import com.xcjw.com.CallBack.CallBackUtils;
import com.xcjw.com.CallBack.FragmentCallback;
import com.xcjw.com.Http.HttpUrl;
import com.xcjw.com.Hy.DemoHelper;
import com.xcjw.com.MainActivity;
import com.xcjw.com.R;
import com.xcjw.com.Utils.CodeUtils;
import com.xcjw.com.Utils.FileUtils;
import com.xcjw.com.Utils.JsonUtil;
import com.xcjw.com.Utils.LogUtil;
import com.xcjw.com.Utils.StatusBarUtil;
import com.xcjw.com.Utils.ToastUtils;
import com.xcjw.com.View.CustomDialog;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * @packname com.xcjw.com.Activity
 * @filename LoginActivity
 * @date on 2018/11/17 17:49
 *****/
public class LoginActivity extends AppCompatActivity  implements FragmentCallback {


      @BindView(R.id.user_name)
      EditText userName;
      @BindView(R.id.user_mima)
      EditText userMima;
      @BindView(R.id.yanzhengma)
      EditText yanzhengma;
      @BindView(R.id.linerlayout)
      LinearLayout linerlayout;
      @BindView(R.id.back)
      RelativeLayout back;
      @BindView(R.id.login)
      TextView login;
      @BindView(R.id.codeimage)
      ImageView codeimage;
      private String s1;
      private String s11;
      private CustomDialog dialog;
      private CustomDialog dialog11;

      @Override
      protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            StatusBarUtil.setRootViewFitsSystemWindows(this, false);
            StatusBarUtil.setTranslucentStatus(this);
            setContentView(R.layout.activity_login);
            ButterKnife.bind(this);
            Myapplication.getInstance().addActivity(this);
            CallBackUtils.setCallBack(this);
            if (Myapplication.sp.getBoolean("isLogin", false)) {
                  Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                  startActivity(intent);
                  this.finish();
            }

            //getCode();
           // s11 = CodeUtils.getInstance().createCode();
           // codeimage.setImageBitmap(CodeUtils.getInstance().createBitmap(CodeUtils.getInstance().createCode()));
           // codeimage.setOnClickListener(new View.OnClickListener() {
//                  @Override
//                  public void onClick(View v) {
//                        s11 = CodeUtils.getInstance().createCode();
//                        // Glide.with(LoginActivity.this).load(CodeUtils.getInstance().createBitmap(CodeUtils.getInstance().createCode())).transform(new GlideRoundTransform(LoginActivity.this,8)).into(codeimage);
//                        codeimage.setImageBitmap(CodeUtils.getInstance().createBitmap(CodeUtils.getInstance().createCode()));
              //    }
          //  });

            login.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View v) {
                        if (Verco()) {
                              Login();
                        }
                  }
            });
            if (Myapplication.sp.getBoolean("isconflected",false)){
                  showiosDialog11();
            }

      }

      private boolean Verco() {
            if (TextUtils.isEmpty(userName.getText().toString())) {
                  Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
                  return false;
            }
            if (TextUtils.isEmpty(userMima.getText().toString())) {
                  Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
                  return false;
            }
//            if (TextUtils.isEmpty(yanzhengma.getText().toString())) {
//                  Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
//                  return false;
//            }

//            if (s11.toLowerCase().equals(yanzhengma.getText().toString().trim().toLowerCase())) {
//                  Toast.makeText(this, "验证码不正确", Toast.LENGTH_SHORT).show();
//                  return false;
//            }
            return true;
      }

      private void showiosDialog() {
            dialog = new CustomDialog(LoginActivity.this, R.style.customDialog, R.layout.ios_dialog_login);
            dialog.show();
            dialog.setCanceledOnTouchOutside(false);
      }

      public String getCode() {
            s11 = new String();
            LoginBean bean = new LoginBean();
            bean.setUsername(userName.getText().toString());
            OkHttpUtils.post(HttpUrl.Url + HttpUrl.GETCODE).upJson(JsonUtil.tojson(bean)).execute(new StringCallback() {
                  @Override
                  public void onSuccess(String s, Call call, Response response) {
                        if (response.code() == 200) {
                              CodeBean codeBean = JsonUtil.parseJsonToBean(s, CodeBean.class);
                              if (codeBean.getCode().equals("0")) {
                                    s11 = codeBean.getContent();
                                    runOnUiThread(new Runnable() {
                                          @Override
                                          public void run() {
                                                codeimage.setImageBitmap(CodeUtils.getInstance().createBitmap(s11));
                                                ;
                                          }
                                    });
                              } else {
                                    ToastUtils.shorttoast(LoginActivity.this, codeBean.getMessage());
                              }
                        } else {
                              ToastUtils.shorttoast(LoginActivity.this, "网络繁忙,请稍后重试");
                        }
                  }

                  @Override
                  public void onError(Call call, Response response, Exception e) {
                        System.out.println("+++++++++++++++++");
                  }
            });


            return s11;
      }

      public void Login() {
            showiosDialog();
            LoginBean bean = new LoginBean();
            bean.setUsername(userName.getText().toString());
            bean.setPassword(userMima.getText().toString());
            OkHttpUtils.post(HttpUrl.Url + HttpUrl.LOGIN).upJson(JsonUtil.tojson(bean)).execute(new StringCallback() {
                  @Override
                  public void onSuccess(String s, Call call, Response response) {
                        if (response.code() == 200) {
                              LoginUser loginUser = JsonUtil.parseJsonToBean(s, LoginUser.class);
                              if (loginUser.getCode().equals("0")) {
                                    login(loginUser.getContent());
                              } else {
                                    if (dialog != null || dialog.isShowing()) {
                                          dialog.dismiss();
                                    }
                                    ToastUtils.shorttoast(LoginActivity.this, loginUser.getMessage());
                              }
                        } else {
                              if (dialog != null || dialog.isShowing()) {
                                    dialog.dismiss();
                              }
                              ToastUtils.shorttoast(LoginActivity.this, "网络繁忙,请稍后重试");
                        }
                  }

                  @Override
                  public void onError(Call call, Response response, Exception e) {
                        if (dialog != null || dialog.isShowing()) {
                              dialog.dismiss();
                        }
                        ToastUtils.shorttoast(LoginActivity.this, "网络繁忙,请稍后重试");
                  }
            });

      }


      private void login(final LoginUser.ContentBean user) {
            try {
                  if (!TextUtils.isEmpty(user.getPhone())) {
                        EMClient.getInstance().login(user.getPhone() + "", user.getPhone() + "123456", new EMCallBack() {
                              @Override
                              public void onSuccess() {
                                    EMClient.getInstance().groupManager().loadAllGroups();
                                    EMClient.getInstance().chatManager().loadAllConversations();
                                    LogUtil.e("环信登录", "成功回调");
                                    Myapplication.editor.putBoolean("isLogin", true).commit();
                                    FileUtils.saveObject(LoginActivity.this, "loginUser", user);
                                    boolean updatenick = EMClient.getInstance().pushManager().updatePushNickname(user.getUserName() == "" ? "" : user.getUserName());
                                    if (!updatenick) {
                                          Log.e("LoginActivity", "update current user nick fail");
                                    }
                                    DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();
                                    if (dialog != null || dialog.isShowing()) {
                                          dialog.dismiss();
                                    }
                                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                    startActivity(intent);
                                    finish();
                              }

                              @Override
                              public void onError(final int i, final String s) {
                                    runOnUiThread(new Runnable() {
                                          @Override
                                          public void run() {
                                                if (dialog != null || dialog.isShowing()) {
                                                      dialog.dismiss();
                                                }
                                                ToastUtils.shorttoast(LoginActivity.this, "登录失败+" + i + s.toString());
                                          }
                                    });

                              }

                              @Override
                              public void onProgress(int i, String s) {

                              }

                        });
                  }
            } catch (Exception e) {
                  LogUtil.e("环信错误", e.getMessage());

            }
      }

      @Override
      public void ondatechange(int position) {
//            if (position == 10) {
//                  showiosDialog11();
//            }
      }
      private void showiosDialog11() {
            dialog11 = new CustomDialog(this, R.style.customDialog, R.layout.login_out);
            dialog11.show();
            TextView tvContent = (TextView) dialog11.findViewById(R.id.textsign);
            tvContent.setText("该账号已在其他地方登录，您被迫下线");
            TextView tvOk = (TextView) dialog11.findViewById(R.id.ok);
            tvOk.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View view) {
                        Myapplication.editor.putBoolean("isconflected",false).commit();
                        dialog11.dismiss();
                  }
            });
      }




}